<template>
  <div class="videoContent" style="width: 650px; height: 490px">
    <div class="handleBtnClass">
      <ElButton @click="handleCut" style="position: absolute; z-index: 1"
      >截图
      </ElButton
      >
    </div>
    <video ref="videoRef" style="width: 640px"></video>
  </div>
  <div style="height: 100px">
    <div class="imageContent" v-for="(item, index) in photoList" :key="index">
      <ElIcon
        @click="handleDel(index)"
        style="
          position: absolute;
          z-index: 1;
          right: 1px;
          color: red;
          cursor: pointer;
        "
      >
        <Close
        />
      </ElIcon>
      <ElImage
        style="height: 100px"
        :src="item"
        :preview-src-list="[item]"
      ></ElImage>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, ref, watch} from "vue";

const photoList = ref<Array<string>>([]);
const canvas = document.createElement("canvas");
const hasPlay = ref(false);
const videoRef = ref<HTMLVideoElement>();

// const props = defineProps<{
//   defaultPhotoList: Array<string>
// }>()
// watch(()=>props.defaultPhotoList,(val)=>{
//   photoList.value = val
// })

onMounted(() => {
  videoRef.value?.addEventListener("loadedmetadata", (event) => {
    console.log(event);
    console.log("煤体加载完毕");
    if (videoRef.value) {
      console.log("video height", videoRef.value.videoHeight);
      console.log("video width", videoRef.value.videoWidth);
      canvas.height = videoRef.value.videoHeight;
      canvas.width = videoRef.value.videoWidth;
    }
    videoRef.value?.play();
  });
  let constraints = {
    video: true,
    audio: false,
  };
  let promise = navigator.mediaDevices.getUserMedia(constraints);
  promise.then((MediaStream) => {
    console.log(MediaStream);
    if (videoRef.value) {
      videoRef.value.srcObject = MediaStream;
      hasPlay.value = true;
    }
  });
});
const handleCut = () => {
  const createCanvas = canvas.getContext("2d");
  if (videoRef.value) {
    createCanvas?.drawImage(videoRef.value, 0, 0, canvas.width, canvas.height);
  }
  photoList.value.push(canvas.toDataURL("image/jpej"));
};
const handleDel = (index) => {
  photoList.value.splice(index, 1);
};
const getPhotoList = () => {
  return photoList.value;
};
const setPhotoList = (data)=>{
  photoList.value = data
}
const clearPhotoList = () => {
  photoList.value = [];
};

defineExpose({getPhotoList, clearPhotoList,setPhotoList});
</script>
<style scoped lang="scss">
.handleBtnClass {
  display: none;
}

.videoContent:hover {
  & > .handleBtnClass {
    display: block;
  }
}

.imageContent {
  margin-left: 5px;
  margin-top: 5px;
  float: left;
  position: relative;
  height: 100px;
  width: 100px;
}
</style>
